import Vue from 'vue'
import Vuex from 'vuex'
import { ShopSeller, ShopRatings } from '../api/shop.js'

Vue.use(Vuex)

export default new Vuex.Store({
  // 储存数据的字段
  state: {
    sellerInfo: null,
    rates: null,
    chooseData: [],
    Bool: false,
    num: 0
  },
  // 只有在当前对象中声明函数才可以操作数据
  mutations: {
    SAVE_SELLER(state, data) {
      state.sellerInfo = data
    },
    SAVE_RATLES(state, data) {
      state.rates = data
    }, // 添加已选中的商品
    ADD_DATA(state, obj) {
      state.Bool = true
      const i = state.chooseData.findIndex(item => item.id === obj.id)
      if (i === -1) {
        state.chooseData.push(obj)
      }
      let count = 1
      for (const k of state.chooseData) {
        count += k.count
      }
      state.num = count
    },
    // 减少已选中的商品
    REDUCE_DATA(state, obj) {
      state.num--
      // state.num = count
      if (obj.count <= 1) {
        const i = state.chooseData.findIndex(item => item.id === obj.id)
        if (i !== -1) {
          // 先让数据初始化为0
          obj.count = 0
          state.chooseData.splice(i, 1)
        }
      }
    },
    // 清空已选择商品
    EMPTY_DATA(state) {
      state.num = 0
      for (const k of state.chooseData) {
        k.count = 0
      }
      state.chooseData = []
    },
    // 动画效果
    EDIT_BOOL(state) {
      state.Bool = false
    }
  },

  // 在vuex中，有一个类似于计算属性的东西，叫做 getters
  getters: {},
  // 异步操作数据
  actions: {
    async GET_SELLER({ commit }) {
      const { data } = await ShopSeller()
      commit('SAVE_SELLER', data)
    },
    async GET_RATLES({ commit }) {
      const data = await ShopRatings()
      console.log(data)
      commit('SAVE_RATLES', data)
    }
  },
  modules: {}
})
